package com.bookmanger.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookmanger.common.result.Result;
import com.bookmanger.common.utils.StringUtils;
import com.bookmanger.entity.Book;
import com.bookmanger.entity.dto.BookSearchDTO;
import com.bookmanger.entity.dto.ModifyBook;
import com.bookmanger.entity.select.BookListDTO;
import com.bookmanger.entity.vo.BookCategoryCountVO;
import com.bookmanger.entity.vo.BookListVo;
import com.bookmanger.entity.vo.ListForm;
import com.bookmanger.mapper.BookMapper;
import com.bookmanger.service.BookSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wei kunJie
 * @date 2024/11/2 14:47:22
 */
@Service
@Slf4j
public class BookSearchServiceImpl extends ServiceImpl<BookMapper, Book> implements BookSearchService {


    @Override
    public Result<List<BookSearchDTO>> search(Book book) {
        //查询
//        List<Book> list = lambdaQuery().eq(StringUtils.isNotNonOrEmpty(book.getBookName()),Book::getBookName, book.getBookName())
//                .eq(StringUtils.isNotNonOrEmpty(book.getAuthor()),Book::getAuthor, book.getAuthor())
//                .eq(StringUtils.isNotNonOrEmpty(book.getISBN()),Book::getISBN, book.getISBN())
//                .eq(book.getCategoryId()!=null,Book::getCategoryId, book.getCategoryId())
//                .list();


        List<Book> list = lambdaQuery()
                .like(StringUtils.isNotNonOrEmpty(book.getBookName()), Book::getBookName, "%" + book.getBookName() + "%")
                .like(StringUtils.isNotNonOrEmpty(book.getAuthor()), Book::getAuthor, "%" + book.getAuthor() + "%")
                .like(StringUtils.isNotNonOrEmpty(book.getISBN()), Book::getISBN, "%" + book.getISBN() + "%")
                .eq(book.getCategoryId() != null, Book::getCategoryId, book.getCategoryId())
                .eq(Book::getGrounding,true)//上架的图书
                .list();

        //无数据
        if (list==null||list.isEmpty()){
            return Result.success(new ArrayList<>());
        }
        //处理查询结果
        List<BookSearchDTO> dtos = list.stream()
                .map(book1 -> BeanUtil.copyProperties(book1, BookSearchDTO.class))
                .collect(Collectors.toList());
        return Result.success(dtos);
    }

    @Override
    public Result<BookSearchDTO> detail(Long bookId) {
        Book one = lambdaQuery().eq(Book::getId, bookId).one();
        if (one==null){
            return Result.error("查无此书");
        }
        return Result.success(BeanUtil.copyProperties(one, BookSearchDTO.class));
    }

    @Override
    public Result addBook(BookSearchDTO bookSearchDTO) {
        if(bookSearchDTO.getAmount() <= 0){
            return Result.error("数量不能小于或者等于0");
        }
        if(bookSearchDTO.getCategoryId() == null){
            return Result.error("添加失败，分类不正确");
        }
        Book book = new Book();
        //bookSearchDTO.setId(0L);//设置id
        bookSearchDTO.setCreateTime(LocalDateTime.now());
        bookSearchDTO.setUpdateTime(LocalDateTime.now());
        BeanUtil.copyProperties(bookSearchDTO,book);
        //写死
        if(!StringUtils.isNotNonOrEmpty(bookSearchDTO.getPicture())){
            book.setPicture("https://img1.baidu.com/it/u=2710708513,225241024&fm=253&fmt=auto&app=138&f=JPEG?w=142&h=189");
        }
        if(!StringUtils.isNotNonOrEmpty(bookSearchDTO.getCover())){
            book.setCover("https://img1.baidu.com/it/u=2710708513,225241024&fm=253&fmt=auto&app=138&f=JPEG?w=142&h=189");
        }
        book.setGrounding(true);
        int insert = baseMapper.insert(book);
        if(insert != 0){
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    @Override
    @Transactional
    public Result updateBook(ModifyBook bookSearch) {
        log.info("bookSearch" + bookSearch.toString());
        if(bookSearch.getId() == null) {
            return Result.error("id为空");
        }
        if(bookSearch.getAmount() != null &&bookSearch.getAmount() < 0){
            return Result.error("数量不能小于0");
        }
        Book book = new Book();
        BeanUtil.copyProperties(bookSearch,book);
        book.setUpdateTime(LocalDateTime.now());
        int update = baseMapper.updateById(book);
        log.info("updateBook" + book);
        if (update != 0){
            //下架图书
            if(book.getAmount() == 0){
                unGroundBook(book.getId());
            }
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    @Override
    public Result groundBook(Long id) {
        if(id == null) {
            return Result.error("id为空");
        }
        UpdateWrapper<Book> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("grounding", true);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("上架成功");
        } else {
            return Result.error("上架失败");
        }
    }

    @Override
    public Result unGroundBook(Long id) {
        if(id == null) {
            return Result.error("id为空");
        }
        UpdateWrapper<Book> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("grounding", false);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("下架成功");
        } else {
            return Result.error("下架失败");
        }
    }

    @Override
    public Result deleteBook(Long id) {
        int delete = baseMapper.deleteById(id);
        if(delete == 0){
            return Result.error("删除失败");
        } else {
            return Result.success("删除成功");
        }
    }

    @Override
    public Integer modifyInventory(Long id, int num) {
        Book book = baseMapper.selectById(id);
        book.setAmount(book.getAmount() +  num);
        return baseMapper.updateById(book);
    }

    @Override
    public Result<ListForm<BookListVo>> getBookList(BookListDTO bookListDTO) {
        log.info("bookListDTO:" + bookListDTO.toString());
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotNonOrEmpty(bookListDTO.getBookName())) {
            queryWrapper.eq("book_name", bookListDTO.getBookName());
        }
        if (StringUtils.isNotNonOrEmpty(bookListDTO.getCategoryId())) {
            queryWrapper.eq("category_id", bookListDTO.getCategoryId());
        }
        if (bookListDTO.getGrounding() != null) {
            queryWrapper.eq("grounding", bookListDTO.getGrounding());
        }
        Page<Book> bookPage = new Page<>(bookListDTO.getPage(), bookListDTO.getSize());
        IPage<Book> bookIPage = page(bookPage, queryWrapper);
        List<Book> bookList = bookIPage.getRecords();
        List<BookListVo> bookListVoList = bookList.stream().map(book -> {
            BookListVo vo = new BookListVo();
            BeanUtil.copyProperties(book, vo);
            return vo;
        }).toList();
        ListForm<BookListVo> bookListForm = new ListForm<>(bookListDTO.getPage(),bookListDTO.getSize(),
                bookIPage.getPages(), //总页数
                bookIPage.getTotal(), //总记录数
                bookListVoList);
        return Result.success(bookListForm);
    }

    @Override
    public Result<Integer> getBookCount() {
        Integer count = Math.toIntExact(baseMapper.selectCount(null));
        return Result.success(count);
    }

    @Override
    public Result<List<BookCategoryCountVO>> getBookCategoryCount() {
        return Result.success(baseMapper.getBookCategoryCount());
    }
}
